//
//  RSDistrictPickerViewController.m
//  iAccountBook
//
//  Created by 侯伟 on 2020/4/7.
//  Copyright © 2020 侯伟. All rights reserved.
//

#import "RSDistrictPickerViewController.h"
#import "UIView+Border.h"


#define progress_w PX(30)

#define title_w  PX(80)

#define list_height PX(340)


@interface RSDistrictPickerViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>

/// 标题
@property(nonatomic,weak)UILabel* titleLb;

/// 关闭按钮
@property(nonatomic,weak)UIButton* closeBtn;

/// 进度条
@property(nonatomic,weak)UIView* progressView;

/// 承载选择Button
@property(nonatomic,weak)MyLinearLayout* btnLayout;

/// 滚动视图
@property(nonatomic,weak)UIScrollView* scrollView;

/**保存所有的button*/
@property(nonatomic,strong) NSMutableArray<UIButton*>*  btnArr;

/**保存所有的tableView*/
@property(nonatomic,strong) NSMutableArray<UITableView*>*  listArr;

/**所有*/
@property(nonatomic,strong) NSArray<RSDistrict*>* dataArr;

/**省数据*/
@property(nonatomic,copy) NSArray*  provinces;
/**市数据*/
@property(nonatomic,copy) NSArray*  cities;
/**区数据*/
@property(nonatomic,copy) NSArray*  districts;


@end

static  NSString* const CellID = @"REAddressID";

@implementation RSDistrictPickerViewController

- (NSArray<RSDistrict*>*)dataArr{
    if(!_dataArr.count || !_dataArr.count){
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"pca-code" ofType:@"plist"];
        NSArray * jsonArray = [NSArray arrayWithContentsOfFile:plistPath];
        _dataArr = [NSArray yy_modelArrayWithClass:RSDistrict.class json:jsonArray];
    }
    return _dataArr;
}

-(NSMutableArray<UITableView*>*)listArr{
    if (!_listArr) {
        _listArr = [NSMutableArray  array];
    }
    return _listArr;
}

-(NSMutableArray<UIButton*>*)btnArr{
    if (!_btnArr) {
        _btnArr = [NSMutableArray  array];
    }
    return _btnArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initSubViews];
    
    self.provinces = self.dataArr;
}


-(void)initSubViews{
    
    MyLinearLayout* popView = [[MyLinearLayout alloc] initWithOrientation:MyOrientation_Vert];
    popView.backgroundColor = UIColor.whiteColor;
    popView.myHorzMargin = 0;
    popView.myBottom = 0;
    popView.myHeight = MyLayoutSize.wrap;
    [self.view addSubview:popView];
    self.popView = popView;
    
    popView.endLayoutBlock = ^{
        [self.popView setCornerRadius:(UIRectCornerTopLeft|UIRectCornerTopRight) size:CGSizeMake(PX(12), PX(12))];
        self.popView.layer.masksToBounds = YES;
    };
    
    //标题栏
    MyRelativeLayout* titleView = [MyRelativeLayout new];
    titleView.myMargin = 0;
    titleView.myHeight = PX(60);
    [self.popView addSubview:titleView];
    
    MyBorderline* separator1 = [MyBorderline new];
    separator1.color = COLOR_GRAY_LINE;
    separator1.thick = 1.0;
    titleView.bottomBorderline = separator1;
    
    UILabel* titleLb = [UILabel lableWithFont:FONT_FIT(16) color:COLOR_BLACK_DARK text:@"地区选择"];
    titleLb.textAlignment = NSTextAlignmentCenter;
    titleLb.myCenterX = 0;
    titleLb.myCenterY = 0;
    [titleView addSubview:titleLb];
    _titleLb = titleLb;
    
    //右侧取消
    UIButton* closeBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
    [closeBtn addTarget:self action:@selector(dismiss:) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn setImage:[UIImage  imageNamed:@"common_nav_close"] forState:UIControlStateNormal];
    closeBtn.myRight = 0;
    closeBtn.myCenterY = 0;
    closeBtn.mySize = CGSizeMake(PX(40), PX(40));
    [titleView addSubview:closeBtn];
    _closeBtn = closeBtn;
    
    //Itmes
    MyLinearLayout* btnLayout = [[MyLinearLayout alloc] initWithOrientation:MyOrientation_Horz];
    btnLayout.padding = UIEdgeInsetsMake(0, 20, 0, 20);
    btnLayout.subviewHSpace = 10.0;
    btnLayout.gravity = MyGravity_Horz_Fill;
    btnLayout.myMargin = 0;
    btnLayout.myHeight = PX(55);
    [popView addSubview:btnLayout];
    _btnLayout = btnLayout;
    
    MyBorderline* separator2 = [MyBorderline new];
    separator2.color = COLOR_GRAY_LINE;
    separator2.thick = 1.0;
    btnLayout.bottomBorderline = separator2;
    
    
    //progressView
    UIView* progressView = [[UIView alloc] initWithFrame:CGRectMake(0, PX(55)-PX(2), progress_w, PX(2.0))];
    progressView.backgroundColor = COLOR_THEME;
    progressView.useFrame = YES;
    [btnLayout addSubview:progressView];
    self.progressView = progressView;
    
    UIScrollView* scrollView = [UIScrollView new];
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.delegate = self;
    scrollView.pagingEnabled = YES;
    scrollView.myMargin = 0;
    scrollView.myHeight = list_height;
    [popView addSubview:scrollView];
    _scrollView = scrollView;
    
    [self initItems];
}

- (void)initItems{
    
    for (int i = 0; i < 3; i++) {
        
        UIButton* titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [titleBtn setTitleColor:COLOR_GRAY_BASE forState:UIControlStateNormal];
        [titleBtn setTitleColor:COLOR_THEME forState:UIControlStateSelected];
        titleBtn.titleLabel.font = FONTMID_FIT(16);
        titleBtn.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [titleBtn setTitle:@"请选择" forState:UIControlStateNormal];
        titleBtn.tag = 100+i;
        titleBtn.myCenterY = 0;
        titleBtn.myLeft = 0;
        titleBtn.mySize = CGSizeMake(title_w, PX(40));
        
        [self.btnArr addObject:titleBtn];
        
        
        UITableView* tableView = [UITableView new];
        tableView.tag = 1000+i;
        tableView.frame = CGRectMake(SCREEN_WIDTH*i, 0, SCREEN_WIDTH, list_height);
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.rowHeight = PX(55);
        tableView.showsVerticalScrollIndicator = NO;//滚动条
        tableView.showsHorizontalScrollIndicator = NO;//滚动条
        tableView.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20);
        //注册cell
        [tableView registerClass:UITableViewCell.class forCellReuseIdentifier:CellID];
        [self.listArr addObject:tableView];
        tableView.tableFooterView = [UIView new];
    }
}

#pragma mark  -- setter

//省列表
- (void)setProvinces:(NSArray *)provinces{
    _provinces = provinces;
    if(provinces.count){
        [self addItemAtIndex:0];
    }else{
        [self removeItemAtIndex:0];
    }
}
//市列表
- (void)setCities:(NSArray *)cities{
    _cities = cities;
    if(cities.count){
        [self addItemAtIndex:1];
    }else{
        [self removeItemAtIndex:1];
    }
}

//区县列表
- (void)setDistricts:(NSArray *)districts{
    _districts = districts;
    if(districts.count){
        [self addItemAtIndex:2];
        
    }else{
        [self removeItemAtIndex:2];
    }
}

//选择省
- (void)setProvice:(RSDistrict *)provice{
    _provice = provice;
    
//    [self setModel:provice atIndex:0];
//
//    self.district = NULL;
//    self.city = NULL;
//    self.districts = NULL;
//
//    self.cities = NULL;
    
    for (RSDistrict* p in self.dataArr) {
        if([p.code isEqualToString:provice.code]){
            
            self.district = NULL;
            self.city = NULL;
            self.districts = NULL;
            
            self.cities = p.children;
            
            [self setModel:provice atIndex:0];
            
            break;
        }
    }
}
//选择市
- (void)setCity:(RSDistrict *)city{
    _city = city;
//    [self setModel:city atIndex:1];
    
//    self.district = NULL;
//    self.districts = NULL;
    
    for (RSDistrict* c in self.cities) {
        if([c.code isEqualToString:city.code]){
            
            self.district = NULL;
            
            self.districts = c.children;
            
            [self setModel:city atIndex:1];
            break;;
        }
    }
}

//选择区
- (void)setDistrict:(RSDistrict *)district{
    _district = district;
    
    [self setModel:district atIndex:2];
}

#pragma mark -- private

/// 添加按钮 列表
/// @param index index description
- (void)addItemAtIndex:(NSInteger)index{
    
    UIButton* btn = self.btnArr[index];
    if(!btn.superview)
        [self.btnLayout insertSubview:btn atIndex:index];
    
    UITableView* list = self.listArr[index];
    if(!list.superview){
        [self.scrollView insertSubview:list atIndex:index];
    }
    self.scrollView.contentSize = CGSizeMake((index+1)*SCREEN_WIDTH, 0);
    
    [self moveToIndex:index];
}

/// 移除列表 按钮
/// @param index index description
- (void)removeItemAtIndex:(NSInteger)index{
    
    UIButton* btn = self.btnArr[index];
    if(btn.superview){
        [btn removeFromSuperview];
    }
    UITableView* list = self.listArr[index];
    if(list.superview){
        [list removeFromSuperview];
    }
    
    if(index - 1 >= 0){
        [self moveToIndex:index-1];
    }
}

/// 设置显示信息
/// @param model 数据模型
/// @param index 位置
- (void)setModel:(RSDistrict*)model atIndex:(NSInteger)index{
    
    UIButton* btn = self.btnArr[index];
    if(model)
        [btn setTitle:model.name forState:UIControlStateNormal];
    else
        [btn setTitle:@"请选择" forState:UIControlStateNormal];
    
    [self.btnArr enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.selected = index == idx;
    }];
}

- (void)moveToIndex:(NSInteger)index{
    
    [self.scrollView setContentOffset:CGPointMake(SCREEN_WIDTH*index, 0) animated:YES];
    
    if(self.btnLayout.subviews.count == 0){
        self.progressView.visibility = MyVisibility_Gone;
    }else{
        self.progressView.visibility = MyVisibility_Visible;
    }
    
    
    
    CGFloat itemW = (SCREEN_WIDTH - 20*2 -(self.btnLayout.subviews.count-2)*10)/(self.btnLayout.subviews.count-1);
    
    CGFloat x = 20 + (itemW+10)*index + (itemW-progress_w)/2.0;
    
    CGRect frame = self.progressView.frame;
    frame.origin.x = x;
    self.progressView.frame = frame;
    
    [self.listArr[index] reloadData];
}




#pragma mark ----UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == self.listArr[0]) {
        return self.provinces.count;
    }else if (tableView == self.listArr[1]){
        return  self.cities.count;
    }else if (tableView == self.listArr[2]){
        return self.districts.count;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID forIndexPath:indexPath];
    RSDistrict*  district;
    RSDistrict* currentDistrict;
    
    if (tableView == self.listArr[0]) {
        district = self.provinces[indexPath.row];
        currentDistrict = self.provice;
    }else if (tableView == self.listArr[1]){
        district = self.cities[indexPath.row];
        currentDistrict = self.city;
    }else if (tableView == self.listArr[2]){
        district = self.districts[indexPath.row];
        currentDistrict = self.district;
    }
    cell.textLabel.text = district.name;
    cell.textLabel.font = FONT_FIT(16);
    BOOL shouldSelected = [district.code isEqualToString:currentDistrict.code];
    cell.textLabel.textColor = shouldSelected?COLOR_THEME:COLOR_GRAY_BASE;
    cell.indentationWidth = 20;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (tableView == self.listArr[0]) { //点击了省
        RSDistrict * model = self.provinces[indexPath.row];
        if(![self.provice.code isEqualToString:model.code]){//如果与当前选择的省不通 则重置市、区
            self.provice = model;
        }else{
            [self moveToIndex:1];
        }
    }else if (tableView == self.listArr[1]){  //点击了市

        RSDistrict * model = self.cities[indexPath.row];
        if(![self.city.code isEqualToString:model.code]){//如果与当前选择的市不通 则重置区县
            self.city = model;
        }else{
            [self moveToIndex:2];
        }
    }else if (tableView == self.listArr[2]){  //点击了区
        //保存选中的省信息
        RSDistrict * model = self.districts[indexPath.row];
        if(![self.district.code isEqualToString:model.code]){//如果与当前选择的市不通 则重置区县
            self.district = model;
        }
        WeakSelf
        if (self.DistrictBlock) {
            weakSelf.DistrictBlock(weakSelf.provice ,weakSelf.city,weakSelf.district);
        }
        [self dismissActionSheetController:NULL];
    }
}



#pragma mark ---------------UIScrollViewDelegate-------------------------------
//内容滚动
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (![scrollView isKindOfClass:[UITableView class]]) {
        NSInteger  index = scrollView.contentOffset.x/scrollView.bounds.size.width;
        [self moveToIndex:index];
    }
}


#pragma mark ---------------actions-------------------------------

//点击标题按钮
-(void)titleBtnClick:(UIButton*)titleBtn{
    
    [self moveToIndex:titleBtn.tag-100];
}

/// dismiss
/// @param sender -
- (void)dismiss:(UIButton*)sender{
    [self dismissActionSheetController:NULL];
}

@end
